from flask import Blueprint, jsonify, request, render_template
from python.extensions import db
from python.model.weather import WeatherData
from datetime import datetime, date
from sqlalchemy import func, extract
import traceback

# 创建温度地图蓝图
map_bp = Blueprint('temperature_map', __name__, url_prefix='/map')

# 使用提供的城市映射表
city_mapping = {
    "上海": "上海市", "北京": "北京市", "天津": "天津市", "重庆": "重庆市",
    "石家庄": "河北省", "太原": "山西省", "呼和浩特": "内蒙古自治区",
    "沈阳": "辽宁省", "长春": "吉林省", "哈尔滨": "黑龙江省",
    "南京": "江苏省", "杭州": "浙江省", "合肥": "安徽省",
    "福州": "福建省", "南昌": "江西省", "济南": "山东省",
    "郑州": "河南省", "武汉": "湖北省", "长沙": "湖南省",
    "广州": "广东省", "南宁": "广西壮族自治区", "海口": "海南省",
    "成都": "四川省", "贵阳": "贵州省", "昆明": "云南省",
    "拉萨": "西藏自治区", "西安": "陕西省", "兰州": "甘肃省",
    "西宁": "青海省", "银川": "宁夏回族自治区", "乌鲁木齐": "新疆维吾尔自治区",
    "澳门": "澳门特别行政区", "香港": "香港特别行政区",
    "高雄": "台湾省"
}


@map_bp.route('/page', methods=['GET'])
def map_page():
    """渲染中国城市温度分布图页面"""
    try:
        # 获取所有城市（过滤空值）
        cities_query = db.session.query(WeatherData.city).distinct().all()
        cities = [city[0] for city in cities_query if city[0] and city[0].strip()] if cities_query else []

        # 获取所有年份（过滤空值）
        years_query = db.session.query(extract('year', WeatherData.date)).distinct().all()
        years = [int(year[0]) for year in years_query if year[0] is not None] if years_query else []
        years = sorted(years, reverse=True)

        # 从城市数据中推断省份
        provinces = set()
        for city in cities:
            # 尝试从城市名称中提取映射的省份
            province = None
            for city_prefix, province_name in city_mapping.items():
                if city_prefix in city:
                    province = province_name
                    break

            if province:
                provinces.add(province)

        provinces = sorted(list(provinces))

        return render_template('menu/map.html',
                               cities=cities,
                               years=years,
                               provinces=provinces)

    except Exception as e:
        print(f"Error rendering map page: {str(e)}")
        print(traceback.format_exc())
        return jsonify({
            "error": "Failed to render map page",
            "message": str(e),
            "traceback": traceback.format_exc()
        }), 500


@map_bp.route('/high_temp_data', methods=['GET'])
def get_high_temp_data():
    """获取最高温度数据，支持按城市和日期筛选"""
    try:
        city = request.args.get('city')
        date_param = request.args.get('date')

        query = db.session.query(
            WeatherData.city,
            func.max(WeatherData.max_temp).label('max_temp')
        )

        # 应用筛选条件
        if city:
            query = query.filter(WeatherData.city == city)
        if date_param:
            # 检查日期是否为具体日期或年份
            if len(date_param) == 4:  # 年份格式
                query = query.filter(extract('year', WeatherData.date) == int(date_param))
            else:  # 具体日期格式
                query = query.filter(WeatherData.date == date_param)

        # 按城市分组
        query = query.group_by(WeatherData.city)

        results = query.all()

        # 格式化数据
        data = []
        for item in results:
            if item.max_temp is not None:
                # 从城市推断省份
                province = None
                for city_prefix, province_name in city_mapping.items():
                    if city_prefix in item.city:
                        province = province_name
                        break

                if province:
                    data.append({
                        "name": province,
                        "value": float(item.max_temp),
                        "city": item.city
                    })

        return jsonify(data)

    except Exception as e:
        print(f"Error fetching high temp data: {str(e)}")
        print(traceback.format_exc())
        return jsonify({
            "error": "Failed to fetch high temp data",
            "message": str(e)
        }), 500


@map_bp.route('/low_temp_data', methods=['GET'])
def get_low_temp_data():
    """获取最低温度数据，支持按城市和日期筛选"""
    try:
        city = request.args.get('city')
        date_param = request.args.get('date')

        query = db.session.query(
            WeatherData.city,
            func.min(WeatherData.min_temp).label('min_temp')
        )

        # 应用筛选条件
        if city:
            query = query.filter(WeatherData.city == city)
        if date_param:
            if len(date_param) == 4:  # 年份格式
                query = query.filter(extract('year', WeatherData.date) == int(date_param))
            else:  # 具体日期格式
                query = query.filter(WeatherData.date == date_param)

        # 按城市分组
        query = query.group_by(WeatherData.city)

        results = query.all()

        # 格式化数据
        data = []
        for item in results:
            if item.min_temp is not None:
                # 从城市推断省份
                province = None
                for city_prefix, province_name in city_mapping.items():
                    if city_prefix in item.city:
                        province = province_name
                        break

                if province:
                    data.append({
                        "name": province,
                        "value": float(item.min_temp),
                        "city": item.city
                    })

        return jsonify(data)

    except Exception as e:
        print(f"Error fetching low temp data: {str(e)}")
        print(traceback.format_exc())
        return jsonify({
            "error": "Failed to fetch low temp data",
            "message": str(e)
        }), 500


@map_bp.route('/city_data', methods=['GET'])
def get_city_data():
    """获取城市级温度数据，用于详细信息展示"""
    try:
        city = request.args.get('city')
        date_param = request.args.get('date')

        query = db.session.query(
            WeatherData.city,
            WeatherData.max_temp,
            WeatherData.min_temp,
            WeatherData.date,
            WeatherData.weather,
            WeatherData.wind_level
        )

        # 应用筛选条件
        if city:
            query = query.filter(WeatherData.city == city)
        if date_param:
            query = query.filter(WeatherData.date == date_param)

        results = query.all()

        # 格式化数据
        data = []
        for item in results:
            data.append({
                "city": item.city,
                "max_temp": float(item.max_temp) if item.max_temp is not None else None,
                "min_temp": float(item.min_temp) if item.min_temp is not None else None,
                "date": item.date.strftime('%Y-%m-%d') if item.date else None,
                "weather": item.weather,
                "wind_level": item.wind_level
            })

        return jsonify(data)

    except Exception as e:
        print(f"Error fetching city data: {str(e)}")
        print(traceback.format_exc())
        return jsonify({
            "error": "Failed to fetch city data",
            "message": str(e)
        }), 500